package com.dongdongshop.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.dongdongshop.service.SMSService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SMSServiceImpl implements SMSService {

    @Autowired
    private AsyncClient client;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public void sendPhoneMessage(String phoneNum) throws Exception {

        // Parameter settings for API request
        String num = RandomUtil.randomNumbers(6);

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phoneNum)
                .signName("东科创想")
                .templateCode("SMS_162522027")
                .templateParam("{\"sms_code\":\"" + num + "\"}")
                // Request-level configuration rewrite, can set Http request parameters, etc.
                // .requestConfiguration(RequestConfiguration.create().setHttpHeaders(new HttpHeaders()))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println(new Gson().toJson(resp));
        //短信验证码发送成功后，将验证码保存到redis中, 并使用电话号码phoneNum作为key
        redisTemplate.boundValueOps(phoneNum).set(num);
        //设置过期时间为30分钟
        redisTemplate.expire(phoneNum,30, TimeUnit.MINUTES);

    }
}
